package com.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.category.entity.DateKeyword;
import com.category.mapper.DateKeywordMapper;
import com.category.service.DateKeywordService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DateKeywordServiceImpl extends ServiceImpl<DateKeywordMapper, DateKeyword> implements DateKeywordService {
    
    @Override
    public List<DateKeyword> getByDate(String dateStr) {
        LambdaQueryWrapper<DateKeyword> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DateKeyword::getDateStr, dateStr)
               .orderByAsc(DateKeyword::getCategoryId);
        return list(wrapper);
    }
    
    @Override
    public List<DateKeyword> getAllKeywords() {
        LambdaQueryWrapper<DateKeyword> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(DateKeyword::getDateStr)
               .orderByAsc(DateKeyword::getCategoryId);
        return list(wrapper);
    }
    
    @Override
    public boolean addKeyword(DateKeyword dateKeyword) {
        // 检查是否已存在相同日期和分类
        LambdaQueryWrapper<DateKeyword> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DateKeyword::getDateStr, dateKeyword.getDateStr())
               .eq(DateKeyword::getCategoryId, dateKeyword.getCategoryId());
        
        if (count(wrapper) > 0) {
            throw new RuntimeException("该日期该分类已存在关键词");
        }
        
        dateKeyword.setCreateTime(LocalDateTime.now());
        dateKeyword.setUpdateTime(LocalDateTime.now());
        return save(dateKeyword);
    }
    
    @Override
    public boolean updateKeyword(DateKeyword dateKeyword) {
        dateKeyword.setUpdateTime(LocalDateTime.now());
        return updateById(dateKeyword);
    }
    
    @Override
    public boolean deleteKeyword(Long id) {
        return removeById(id);
    }
}
